<template>
  <d-modal
    v-model="visible"
    :show-close="true"
    :close-on-click-overlay="true"
    width="440px"
    class="auth-modal"
  >
    <template #header>
      <div class="modal-header">
        <div class="modal-logo">
          <img src="/logo.svg" alt="MateChat" class="logo">
          <h3>{{ isLoginMode ? $t('auth.loginTitle') : $t('auth.registerTitle') }}</h3>
        </div>
      </div>
    </template>
    
    <div class="modal-content">
      <div v-if="isLoginMode" class="auth-form">
        <div class="form-header">
          <p>{{ $t('auth.loginSubtitle') }}</p>
        </div>
        
        <form @submit.prevent="handleLogin" class="form-content">
          <div class="form-group">
            <d-input
              v-model="loginForm.email"
              type="email"
              :placeholder="$t('auth.emailPlaceholder')"
              :error="loginErrors.email"
              size="lg"
              prefix-icon="email"
              required
            >
              <template #prefix>
                <d-icon name="email" size="16px" />
              </template>
            </d-input>
            <div v-if="loginErrors.email" class="error-message">
              <d-icon name="error" size="14px" />
              {{ loginErrors.email }}
            </div>
          </div>
          
          <div class="form-group">
            <d-input
              v-model="loginForm.password"
              type="password"
              :placeholder="$t('auth.passwordPlaceholder')"
              :error="loginErrors.password"
              size="lg"
              prefix-icon="lock"
              show-password
              required
            >
              <template #prefix>
                <d-icon name="lock" size="16px" />
              </template>
            </d-input>
            <div v-if="loginErrors.password" class="error-message">
              <d-icon name="error" size="14px" />
              {{ loginErrors.password }}
            </div>
          </div>
          
          <div class="form-options">
            <d-checkbox v-model="rememberMe" size="sm">
              {{ $t('auth.rememberMe') }}
            </d-checkbox>
            <a href="#" class="forgot-password">{{ $t('auth.forgotPassword') }}</a>
          </div>
          
          <d-button
            type="submit"
            variant="solid"
            color="primary"
            :loading="authStore.isLoading"
            :disabled="!isLoginFormValid"
            size="lg"
            class="auth-button"
          >
            <template #icon>
              <d-icon name="login" size="16px" />
            </template>
            {{ $t('auth.loginButton') }}
          </d-button>
          
          <div class="divider">
            <span>{{ $t('auth.orLoginWith') }}</span>
          </div>
          
          <div class="social-auth">
            <d-button variant="outline" size="lg" class="social-button">
              <template #icon>
                <d-icon name="github" size="18px" />
              </template>
              GitHub
            </d-button>
            <d-button variant="outline" size="lg" class="social-button">
              <template #icon>
                <d-icon name="google" size="18px" />
              </template>
              Google
            </d-button>
          </div>
        </form>
        
        <div class="form-footer">
          <p>
            {{ $t('auth.noAccount') }}
            <a href="#" @click.prevent="switchToRegister" class="link">
              {{ $t('auth.registerNow') }}
            </a>
          </p>
        </div>
      </div>
      
      <div v-else class="auth-form">
        <div class="form-header">
          <p>{{ $t('auth.registerSubtitle') }}</p>
        </div>
        
        <form @submit.prevent="handleRegister" class="form-content">
          <div class="form-group">
            <d-input
              v-model="registerForm.name"
              type="text"
              :placeholder="$t('auth.namePlaceholder')"
              :error="registerErrors.name"
              size="lg"
              prefix-icon="user"
              required
            >
              <template #prefix>
                <d-icon name="user" size="16px" />
              </template>
            </d-input>
            <div v-if="registerErrors.name" class="error-message">
              <d-icon name="error" size="14px" />
              {{ registerErrors.name }}
            </div>
          </div>
          
          <div class="form-group">
            <d-input
              v-model="registerForm.email"
              type="email"
              :placeholder="$t('auth.emailPlaceholder')"
              :error="registerErrors.email"
              size="lg"
              prefix-icon="email"
              required
            >
              <template #prefix>
                <d-icon name="email" size="16px" />
              </template>
            </d-input>
            <div v-if="registerErrors.email" class="error-message">
              <d-icon name="error" size="14px" />
              {{ registerErrors.email }}
            </div>
          </div>
          
          <div class="form-group">
            <d-input
              v-model="registerForm.password"
              type="password"
              :placeholder="$t('auth.passwordPlaceholder')"
              :error="registerErrors.password"
              size="lg"
              prefix-icon="lock"
              show-password
              required
            >
              <template #prefix>
                <d-icon name="lock" size="16px" />
              </template>
            </d-input>
            <div v-if="registerErrors.password" class="error-message">
              <d-icon name="error" size="14px" />
              {{ registerErrors.password }}
            </div>
          </div>
          
          <div class="form-group">
            <d-input
              v-model="confirmPassword"
              type="password"
              placeholder="确认密码"
              :error="registerErrors.confirmPassword"
              size="lg"
              prefix-icon="lock"
              show-password
              required
            >
              <template #prefix>
                <d-icon name="lock" size="16px" />
              </template>
            </d-input>
            <div v-if="registerErrors.confirmPassword" class="error-message">
              <d-icon name="error" size="14px" />
              {{ registerErrors.confirmPassword }}
            </div>
          </div>
          
          <div class="form-agreement">
            <d-checkbox v-model="agreedToTerms" size="sm">
              我已阅读并同意
              <a href="#" class="agreement-link">服务条款</a>
              和
              <a href="#" class="agreement-link">隐私政策</a>
            </d-checkbox>
          </div>
          
          <d-button
            type="submit"
            variant="solid"
            color="primary"
            :loading="authStore.isLoading"
            :disabled="!isRegisterFormValid"
            size="lg"
            class="auth-button"
          >
            <template #icon>
              <d-icon name="user-add" size="16px" />
            </template>
            {{ $t('auth.registerButton') }}
          </d-button>
          
          <div class="divider">
            <span>{{ $t('auth.orRegisterWith') }}</span>
          </div>
          
          <div class="social-auth">
            <d-button variant="outline" size="lg" class="social-button">
              <template #icon>
                <d-icon name="github" size="18px" />
              </template>
              GitHub
            </d-button>
            <d-button variant="outline" size="lg" class="social-button">
              <template #icon>
                <d-icon name="google" size="18px" />
              </template>
              Google
            </d-button>
          </div>
        </form>
        
        <div class="form-footer">
          <p>
            {{ $t('auth.hasAccount') }}
            <a href="#" @click.prevent="switchToLogin" class="link">
              {{ $t('auth.loginNow') }}
            </a>
          </p>
        </div>
      </div>
    </div>
  </d-modal>
</template>

<script setup lang="ts">
import { reactive, computed, watch, ref } from 'vue';
import { useAuthStore } from '@/store';
import type { LoginRequest, RegisterRequest } from '@/types/auth';

interface Props {
  visible: boolean;
  mode?: 'login' | 'register';
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'login',
});

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'auth-success': [];
}>();

const authStore = useAuthStore();
const rememberMe = ref(false);
const confirmPassword = ref('');
const agreedToTerms = ref(false);

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const isLoginMode = ref(props.mode === 'login');

const loginForm = reactive<LoginRequest>({
  email: '',
  password: '',
});

const registerForm = reactive<RegisterRequest>({
  name: '',
  email: '',
  password: '',
});

const loginErrors = reactive({
  email: '',
  password: '',
});

const registerErrors = reactive({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
});

const isLoginFormValid = computed(() => {
  return loginForm.email && loginForm.password && !loginErrors.email && !loginErrors.password;
});

const isRegisterFormValid = computed(() => {
  return registerForm.name && registerForm.email && registerForm.password && 
         confirmPassword.value && agreedToTerms.value &&
         !registerErrors.name && !registerErrors.email && !registerErrors.password && !registerErrors.confirmPassword;
});

const validateLoginForm = () => {
  loginErrors.email = '';
  loginErrors.password = '';
  
  if (!loginForm.email) {
    loginErrors.email = '请输入邮箱地址';
    return false;
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(loginForm.email)) {
    loginErrors.email = '请输入有效的邮箱地址';
    return false;
  }
  
  if (!loginForm.password) {
    loginErrors.password = '请输入密码';
    return false;
  }
  
  if (loginForm.password.length < 6) {
    loginErrors.password = '密码长度至少6位';
    return false;
  }
  
  return true;
};

const validateRegisterForm = () => {
  registerErrors.name = '';
  registerErrors.email = '';
  registerErrors.password = '';
  registerErrors.confirmPassword = '';
  
  if (!registerForm.name) {
    registerErrors.name = '请输入姓名';
    return false;
  }
  
  if (registerForm.name.length < 2) {
    registerErrors.name = '姓名长度至少2位';
    return false;
  }
  
  if (!registerForm.email) {
    registerErrors.email = '请输入邮箱地址';
    return false;
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerForm.email)) {
    registerErrors.email = '请输入有效的邮箱地址';
    return false;
  }
  
  if (!registerForm.password) {
    registerErrors.password = '请输入密码';
    return false;
  }
  
  if (registerForm.password.length < 6) {
    registerErrors.password = '密码长度至少6位';
    return false;
  }
  
  if (!confirmPassword.value) {
    registerErrors.confirmPassword = '请确认密码';
    return false;
  }
  
  if (registerForm.password !== confirmPassword.value) {
    registerErrors.confirmPassword = '两次输入的密码不一致';
    return false;
  }
  
  if (!agreedToTerms.value) {
    return false;
  }
  
  return true;
};

const handleLogin = async () => {
  if (!validateLoginForm()) {
    return;
  }
  
  const result = await authStore.login(loginForm);
  
  if (result.success) {
    visible.value = false;
    emit('auth-success');
    resetForms();
  } else {
    loginErrors.password = result.error || '登录失败，请重试';
  }
};

const handleRegister = async () => {
  if (!validateRegisterForm()) {
    return;
  }
  
  const result = await authStore.register(registerForm);
  
  if (result.success) {
    visible.value = false;
    emit('auth-success');
    resetForms();
  } else {
    registerErrors.password = result.error || '注册失败，请重试';
  }
};

const switchToLogin = () => {
  isLoginMode.value = true;
  resetErrors();
};

const switchToRegister = () => {
  isLoginMode.value = false;
  resetErrors();
};

const resetForms = () => {
  loginForm.email = '';
  loginForm.password = '';
  registerForm.name = '';
  registerForm.email = '';
  registerForm.password = '';
  confirmPassword.value = '';
  rememberMe.value = false;
  agreedToTerms.value = false;
  resetErrors();
};

const resetErrors = () => {
  loginErrors.email = '';
  loginErrors.password = '';
  registerErrors.name = '';
  registerErrors.email = '';
  registerErrors.password = '';
  registerErrors.confirmPassword = '';
};

// 监听模态框关闭，重置表单
watch(visible, (newVisible) => {
  if (!newVisible) {
    resetForms();
  }
});

// 监听mode变化
watch(() => props.mode, (newMode) => {
  isLoginMode.value = newMode === 'login';
});
</script>

<style scoped lang="scss">
@import "devui-theme/styles-var/devui-var.scss";

:deep(.devui-modal) {
  .devui-modal-content {
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
  }
  
  .devui-modal-header {
    padding: 24px 24px 0;
    border-bottom: none;
  }
  
  .devui-modal-body {
    padding: 0 24px 24px;
  }
}

.modal-header {
  .modal-logo {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .logo {
      width: 32px;
      height: 32px;
    }
    
    h3 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: $devui-text;
      background: linear-gradient(135deg, $devui-brand 0%, $devui-brand-active 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
}

.modal-content {
  padding: 0;
}

.auth-form {
  .form-header {
    text-align: center;
    margin-bottom: 24px;
    
    p {
      margin: 0;
      color: $devui-text-weak;
      font-size: 14px;
      line-height: 1.5;
    }
  }
  
  .form-content {
    .form-group {
      margin-bottom: 16px;
      
      :deep(.devui-input) {
        width: 100%;
        border-radius: 12px;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: $devui-brand;
          box-shadow: 0 0 0 3px rgba($devui-brand, 0.1);
        }
        
        &:focus-within {
          border-color: $devui-brand;
          box-shadow: 0 0 0 3px rgba($devui-brand, 0.2);
        }
      }
      
      .error-message {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-top: 8px;
        font-size: 12px;
        color: $devui-danger;
        font-weight: 500;
      }
    }
    
    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      :deep(.devui-checkbox) {
        font-size: 14px;
        color: $devui-text-weak;
      }
      
      .forgot-password {
        color: $devui-brand;
        text-decoration: none;
        font-size: 14px;
        font-weight: 500;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .form-agreement {
      margin: 12px 0 16px;
      
      :deep(.devui-checkbox) {
        font-size: 14px;
        color: $devui-text-weak;
        line-height: 1.4;
        
        .agreement-link {
          color: $devui-brand;
          text-decoration: none;
          font-weight: 500;
          
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
    
    .auth-button {
      width: 100%;
      height: 44px;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 16px;
      transition: all 0.3s ease;
      
      &:hover:not(:disabled) {
        transform: translateY(-1px);
        box-shadow: 0 8px 20px rgba($devui-brand, 0.3);
      }
    }
    
    .divider {
      position: relative;
      text-align: center;
      margin: 16px 0;
      color: $devui-text-weak;
      font-size: 14px;
      
      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 1px;
        background: $devui-dividing-line;
      }
      
      span {
        background: $devui-base-bg;
        padding: 0 12px;
        position: relative;
        z-index: 1;
      }
    }
    
    .social-auth {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      margin-bottom: 8px;
      
      .social-button {
        height: 40px;
        border-radius: 12px;
        border-color: $devui-dividing-line;
        color: $devui-text;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: $devui-brand;
          color: $devui-brand;
        }
      }
    }
  }
  
  .form-footer {
    margin-top: 16px;
    text-align: center;
    padding-top: 16px;
    border-top: 1px solid $devui-dividing-line;
    
    p {
      margin: 0;
      font-size: 14px;
      color: $devui-text-weak;
    }
    
    .link {
      color: $devui-brand;
      text-decoration: none;
      font-weight: 600;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

@media screen and (max-width: 480px) {
  :deep(.devui-modal) {
    .devui-modal-content {
      margin: 20px;
      width: calc(100% - 40px);
    }
    
    .devui-modal-header {
      padding: 20px 20px 0;
    }
    
    .devui-modal-body {
      padding: 0 20px 20px;
    }
  }
  
  .social-auth {
    grid-template-columns: 1fr;
  }
}
</style>